package com.shopping.controller;

import com.shopping.pojo.Cart;
import com.shopping.pojo.Result;
import com.shopping.security.JwtUtil;
import com.shopping.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//和购物车以及订单相关的
@Slf4j
@RestController
@RequestMapping("/api")
public class CartController {
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private CartService cartService;

    //添加商品至购物车
    @PostMapping("/cart/add")
    public Result addCart(@RequestHeader("Authorization") String token, @RequestBody Cart cart) {
        //@RequestHeader用于获取 HTTP 请求头中 Authorization 字段的注解
        //"Authorization"是请求头的名称

        // 去掉"Bearer "前缀
        token = token.replace("Bearer ", "");

        // 从JWT中提取顾客ID
        Integer customerId = jwtUtil.extractCustomerId(token);
        log.info("添加商品至购物车，顾客id为：{}，商品id为：{}", customerId,cart.getId());
        cartService.addToCart(customerId,cart);
        return Result.success();
    }

    //查询购物车列表
    @GetMapping("/cart/list")
    public Result listCart(@RequestHeader("Authorization") String token) {
        token = token.replace("Bearer ", "");
        Integer customerId = jwtUtil.extractCustomerId(token);
        log.info("查询购物车列表，顾客id为：{}", customerId);
        return Result.success(cartService.getCartList(customerId));
    }
    //查询订单列表
    @GetMapping("/cart/order")
    public Result OrderCart(@RequestHeader("Authorization") String token) {
        token = token.replace("Bearer ", "");
        Integer customerId = jwtUtil.extractCustomerId(token);
        log.info("查询订单列表，顾客id为：{}", customerId);
        return Result.success(cartService.getOrderList(customerId));
    }
    //查询全部订单
    @GetMapping("/adminhome/order")
    public Result allOrder() {
        log.info("查询全部订单");
        return Result.success(cartService.allOrder());
    }

    //修改商品信息（把status改为1或者删除商品或者增加商品数量）
    @PostMapping("/cart/modify")
    public Result modifyCart( @RequestBody List<Cart> carts) {

        log.info("修改商品信息，商品数量为：{}",carts.size());
        cartService.modifyCart(carts);
        return Result.success();
    }
    //删除单条购物车
    @DeleteMapping("/cart/{id}")
    public Result deleteCart(@PathVariable("id") Integer id) {
        log.info("删除购物车：id:{}",id);
        cartService.deleteCart(id);
        return Result.success();
    }
}
